//
//  PersonPhoneViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/8.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "PersonPhoneViewController.h"
#import "TPKeyboardAvoidingTableView.h"
#import "CTextField.h"
@interface PersonPhoneViewController()<UITableViewDataSource,UITableViewDelegate>
{
    TPKeyboardAvoidingTableView *_table;
    CTextField *_passWordTF;
    CTextField *_phoneTF;
    CTextField *_verTF;
    BOOL _hasSendCode;
    NSInteger _eyeClick;

    
}
@property(nonatomic,strong)UIButton *sendBtn;
@end
@implementation PersonPhoneViewController
- (void)initView
{
    [super initView];
    [self setTitle:@"修改手机号"];
    
    _table =[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 64, WindowWidth,WindowHeight-64)];
    _table.sectionHeaderHeight =0;
    _table.delegate =self;
    _table.dataSource =self;
    _table.backgroundColor =BackColor;
    _table.separatorStyle =UITableViewCellSelectionStyleNone;
    
    if(WindowHeight ==480)
    {
        _table.scrollEnabled=YES;
    }else
    {
        _table.scrollEnabled=NO;
    }
    [self.view addSubview:_table];
    
    
    
}
//去掉粘合性
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView ==_table)
    {
        CGFloat sectionHeaderHeight = 39;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 48)];
        view.backgroundColor =[UIColor whiteColor];
        [cell.contentView addSubview:view];
        CTextField *textField =[[CTextField alloc]initWithFrame:CGRectMake(25, 0.5, WindowWidth-50, 47)];
        textField.font =F(12);
        textField.tag =100;
        [view addSubview:textField];
        UILabel *line =[[UILabel alloc]initWithFrame:CGRectMake(0,0, WindowWidth, 0.5)];
        line.tag =200;
        line.backgroundColor=LineColor;
        [view addSubview:line];
        UILabel *line1 =[[UILabel alloc]initWithFrame:CGRectMake(0,48-0.5, WindowWidth, 0.5)];
        line1.tag =300;
        line1.backgroundColor=LineColor;
        [view addSubview:line1];
        
        self.sendBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.sendBtn setBackgroundColor:SendColor];
        self.sendBtn.frame =CGRectMake(WindowWidth-106, 7.5, 86, 33);
        self.sendBtn.layer.masksToBounds=YES;
        self.sendBtn.layer.cornerRadius=4;
        self.sendBtn.userInteractionEnabled =YES;
        [self.sendBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        self.sendBtn.titleLabel.font =[UIFont systemFontOfSize:14];
        self.sendBtn.tag =400;
        [view addSubview:self.sendBtn];
        UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame =CGRectMake(WindowWidth-86, 7.5, 86, 33);
        [button setImage:[UIImage imageNamed:@"Ico_register_noEye"] forState:UIControlStateNormal];
        button.tag=500;
        [cell.contentView addSubview:button];
    }
    CTextField *textField =[cell viewWithTag:100];
    UIButton *btn =[cell viewWithTag:400];
    UIButton *eyeBtn =[cell viewWithTag:500];

    [textField setPlaceholder:@[ @"请输入密码", @"请输入新手机号",@"请输入验证码"][indexPath.section]];
    if (indexPath.section==0) {
        btn.hidden=YES;
        _passWordTF.frame=CGRectMake(25, 0.5, WindowWidth-130, 47);
        _passWordTF =textField;
        _passWordTF.secureTextEntry=YES;
        [_passWordTF setInputType:CTextFieldInputTypePassword];
        [_passWordTF setBk_shouldChangeCharactersInRangeWithReplacementStringBlock:^BOOL(UITextField *textField, NSRange range, NSString *str) {
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
            NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            return [str isEqualToString:filtered];
        }];
        
        [_passWordTF setMinLength:8 msg:@"请输入8-20位密码!"];
        [_passWordTF setMaxLength:20 LengthChangeBlock:nil];
        [_passWordTF bk_addEventHandler:^(id sender) {
            //移除表情
            NSString *newStr= [CClass disable_emoji:_passWordTF.text];
            _passWordTF.text=newStr;
            
            
        } forControlEvents:UIControlEventEditingChanged];
        [eyeBtn bk_addEventHandler:^(id sender) {
            eyeBtn.hidden=NO;
            _eyeClick++;
            if (_eyeClick%2==0) {
                _passWordTF.secureTextEntry=YES;
                [eyeBtn setImage:[UIImage imageNamed:@"Ico_register_noEye"] forState:UIControlStateNormal];
                
            }else{
                _passWordTF.secureTextEntry=NO;
                [eyeBtn setImage:[UIImage imageNamed:@"Ico_register_eye"] forState:UIControlStateNormal];
            }
        } forControlEvents:UIControlEventTouchUpInside];
    }else if(indexPath.section==1)
    {
        eyeBtn.hidden=YES;
        btn.hidden=YES;
        _phoneTF=textField;
        [_phoneTF setInputType:CTextFieldInputTypePhone];
        [_phoneTF setNullMsg:@"请输入11位手机号!"];

    }else if(indexPath.section==2) {
        eyeBtn.hidden=YES;
        btn.hidden=NO;
        textField.frame =CGRectMake(25, 0, WindowWidth-130, 47);
        _verTF=textField;
        _verTF.inputType =CTextFieldInputTypeNum;
        [_verTF setMaxLength:6 LengthChangeBlock:nil];

        [btn bk_addEventHandler:^(id sender) {
            
            if (!_phoneTF.verfiy) {
                return;
            }
            if ([self.phone isEqualToString:_phoneTF.value]) {
                [CClass showMessage:@"该手机号与当前手机号相同!"];
                return;
            }
            //判断注册没有注册 在未注册的情况下发验证码
            [CClass HttpRequestTask:YES withUrl:@"app_registryCheckCaptcha" withData:@{@"mobile":_phoneTF.value,@"isCheckRegistry":@"0",@"customerType":@"02",@"sendIfRegistered":@"1"} notifyError:YES onSuccess:^(BaseModel *model) {
           
                _hasSendCode = true;
                [self.sendBtn setEnabled:NO];
                __block NSInteger t = 60;
                NSTimeInterval period = 1.0; //设置时间间隔
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.sendBtn setTitle:[NSString stringWithFormat:@"%zds", t] forState:UIControlStateNormal];
                        [self.sendBtn setBackgroundColor:[UIColor colorFromHexString:@"b3babd"]];
                        
                    });
                    if (t -- <= 0 ) {
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.sendBtn setEnabled:YES];
                            [self.sendBtn setTitle:@"重发验证码" forState:UIControlStateNormal];
                            [self.sendBtn setBackgroundColor:SendColor];
                        });
                    }
                });
                dispatch_resume(_timer);
                

                
            } onError:^(BaseModel *model) {
                
                //出错时候
            }];
            
            
        } forControlEvents:UIControlEventTouchUpInside];
    }

    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 50;
    }else
    {
        return 39;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==2) {
        return 70;
    }else
    {
        return 0;
    }
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 39)];
    view.backgroundColor =BackColor;
    UILabel *lab =[[UILabel alloc]initWithFrame:CGRectMake(25, 0, 100, 39)];
    lab.font= F(14);
    [view addSubview:lab];
    if (section ==0) {
        view.frame =CGRectMake(0, 0, WindowWidth, 50);
        lab.frame =CGRectMake(25, 11, 100, 39);
    }
    NSArray *ar =[[NSArray alloc]initWithObjects:@"密码",@"新手机",@"验证码", nil];
    lab.text =[ar objectAtIndex:section];
    return view;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 70)];
    view.backgroundColor =BackColor;
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame =CGRectMake(33, 40, WindowWidth-66, 35);
    [button setBackgroundColor:MainColor];
    button.layer.masksToBounds=YES;
    button.layer.cornerRadius=8;
    [button setTitle:@"确定" forState:UIControlStateNormal];
    button.titleLabel.font =F(15);
    [button bk_addEventHandler:^(id sender) {
        if (!_passWordTF.verfiy) {
            return;
        }
        if (_passWordTF.text.length>20) {
            [CClass showMessage:@"请输入8-20位新登录密码!"];
            return;
        }
        if (!_phoneTF.verfiy) {
            return;
        }
        if (_hasSendCode == false) {
            [CClass showMessage:@"请先发送验证码!"];
            return ;
        }
        if (_verTF.value.length==0) {
            [CClass showMessage:@"请输入验证码!"];
            return;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:[CClass getCacheData:NSUD_UUID] forKey:@"uuid"];
        [dic setObject:[CClass base64:_passWordTF.text] forKey:@"password"];
        [dic setObject:_phoneTF.value forKey:@"mobile"];
        [dic setObject:_verTF.text forKey:@"captcha"];
        [self setIsLoading:YES];

        [CClass HttpRequestTask:YES withUrl:@"reviseaccount_mobileCheckPwd" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
            [self setIsLoading:NO];
            [CClass saveCacheData:_phoneTF.value key:NSUD_Mobile];

            [CClass showMessage:@"修改手机号成功"completion:^{
                [self backController];
            }];
            
        } onError:^(BaseModel *model) {
            
            //出错时候
        }];

    } forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    return view;
    
}
@end
